import 'dart:convert';
import 'dart:core';
import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:fate_blind_box/utils/page.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:flutter/foundation.dart';
import 'package:universal_html/html.dart' as html;
import 'http_config.dart';
import 'package:dio/adapter.dart';

class HttpRequest {

  HttpRequest._();

  static final BaseOptions _options = BaseOptions(
    baseUrl: HttpConfig.baseUrl,
    //连接服务器超时时间，单位是毫秒.
    connectTimeout: 10000,
    //响应流上前后两次接受到数据的间隔，单位为毫秒。
    receiveTimeout: 10000,
    //Http请求头.
    headers: {"content-type": "application/json"},
      // connectTimeout: HttpConfig.timeOut
  );

  static final Dio _dio = Dio(_options);

  static Future? request(
      String url,
      {
        String method = 'post',
        String prefixPath = HttpConfig.webApi,
        Map<String, dynamic>? params,
        Interceptor? inter
      }) async {
    // 1.请求的单独配置
    if (HttpConfig.token.isNotEmpty) {
      HttpConfig.token = await Provider.getCache("token");
    }
    final options = Options(method: method, headers: <String, dynamic>{
      "Authorization": HttpConfig.token,
    });
    // print('url：$url \nmethod：$method  \nprefixPath：$prefixPath  \nparams：$params  \ninter：$inter  \nHttpConfig.token：${HttpConfig.token}  \noptions：$options');
    try {
      (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client){
        client.badCertificateCallback=(cert, host, port){
          return true;
        };
      };
      Response response = await _dio.request<String>(
          "$prefixPath/$url",
          data: method.toLowerCase() != 'get' ? params : null,
          queryParameters: method.toLowerCase() == 'get' ? params : null,
          options: options
      );
      if (response.statusCode == 200 || response.data != null) {
        final obj = jsonDecode(response.data);
        if (kDebugMode) {
          print('${HttpConfig.baseUrl}$prefixPath$url');
          log('rx---------${response.data}');
        }

        if (obj['code'] == 403) {
         // Provider.remove('token');
          if (kDebugMode) {
            print('-------------'+obj);
          }
          // Response tokenRes = await Dio(_options).request<String>(
          //     "$prefixPath/${ApiService().login}",
          //     data: { "code": "0000" },
          //     options: Options(method: "post")
          // );
          // final res = jsonDecode(tokenRes.data);
          // final prefs = await SharedPreferences.getInstance();
          // HttpConfig.token = res['data']['token'];
          // prefs.setString("token", HttpConfig.token);
          // prefs.setString("memberId", res['data']['memberId']);
          // return await request(
          //   url,
          //   method : method,
          //   prefixPath : prefixPath,
          //   params : params,
          //   inter : inter
          // );
           //Navigate.toLogin();
        }
        return obj;
      }
      return null;
    } on DioError catch(e) {
      print('dd $e');
      if (e.response?.data != null) {
        final obj = jsonDecode(e.response!.data);
        if (obj?['code'] == 403) {
          // Provider.remove('token');
          if (kDebugMode) {
            print('----------------fffff'+obj.toString());
          }
          if(url != 'member/getMemberSeenNum'){
           // Navigate.toLogin();
          }

        }
        return obj;
      }
      Future.error(e);
      if (kDebugMode) {
        print('${HttpConfig.baseUrl}$prefixPath$url');
        print('rx---------'+e.message);
      }
    }
    return null;
  }

  static Future? uploadFile(
  String url,
  {
    String prefixPath = HttpConfig.webApi,
    required Map<String, dynamic> params,
    ProgressCallback? sendCallback
  }) async{
    final options = Options(headers: <String, dynamic>{
      "Authorization": HttpConfig.token
    });
    try {
      (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client){
        client.badCertificateCallback=(cert, host, port){
          return true;
        };
      };
      Response res = await _dio.post<String>(
        "$prefixPath/$url",
        data: FormData.fromMap(params),
        options: options,
        onSendProgress: sendCallback
      );
      if (res.data != null) {
        return jsonDecode(res.data);
      }
      return null;
    } on DioError catch (e) {
      Future.error(e);
    }
    return null;
  }

  static uploadFileFromHtml(
      String api,
      html.FormData data,
      Function callback,
  ) {
    final res = html.HttpRequest();
    res.open("POST", "${HttpConfig.baseUrl}${HttpConfig.webApi}/$api");
    res.setRequestHeader("Authorization", HttpConfig.token);
    res.send(data);
    res.onLoadEnd.listen((event) {
      callback(jsonDecode(res.response));
    });
  }
}
